package edu.yctc.delivery.controller.impl;

import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import edu.yctc.delivery.constant.ErrorText;
import edu.yctc.delivery.constant.StaticPath;
import edu.yctc.delivery.constant.TemplatePath;
import edu.yctc.delivery.controller.UserController;
import edu.yctc.delivery.controller.session.SessionContentHolder;
import edu.yctc.delivery.controller.verification.VerificationCodeHolder;
import edu.yctc.delivery.entity.ResultDO;
import edu.yctc.delivery.entity.UserDO;
import edu.yctc.delivery.entity.tag.UserTag;
import edu.yctc.delivery.service.PermissionService;
import edu.yctc.delivery.service.UserService;
import edu.yctc.delivery.utils.SHA256Util;
import edu.yctc.delivery.vo.FindPasswordVO;
import edu.yctc.delivery.vo.FrontCaptchaVO;
import edu.yctc.delivery.vo.MailFindPasswordVO;
import edu.yctc.delivery.vo.PhoneFindPasswordVO;
import edu.yctc.delivery.vo.UpdateMailVO;
import edu.yctc.delivery.vo.UpdatePhoneVO;
import edu.yctc.delivery.vo.UserModifyPasswordVO;
import edu.yctc.delivery.vo.UserVO;

/**
 * 
 * @className UserControllerImpl
 * @description userController实现
 * @author zyj
 * @date 2020年1月16日
 *
 */
@Controller
@RequestMapping("/user")
public class UserControllerImpl implements UserController {

    private final static Logger LOG = LoggerFactory.getLogger("controllerLogger");

    @Autowired
    private UserService userService;

    @Autowired
    private PermissionService permissionService;

    @Override
    @GetMapping("logout")
    public String showSignout() {
        return TemplatePath.USER_LOGOUT;
    }

    @Override
    @PostMapping("logout")
    public String signout(HttpSession httpSession) {
        if (StringUtils.isBlank(httpSession.getId())) {
            LOG.error("session error, session={}", httpSession);
            return "redirect:/" + StaticPath.COMMON_ERROR + "?" + ErrorText.PARAMETER_INVALID;
        }
        try {
            long userId = SessionContentHolder.getSignInUserIdBySessionId(httpSession.getId());
            if (userId <= 0) {
                LOG.error("log out error, userId <= 0, sessionId={}", httpSession.getId());
                return "redirect:/" + StaticPath.COMMON_ERROR + "?" + ErrorText.NO_SUCH_USER;
            }
            ResultDO<UserDO> getUserDOByIdResultDO = userService.getUserDOById(userId);
            if (getUserDOByIdResultDO.isSuccess() == false) {
                LOG.error("log out fail, userId={}, session={}, resultDO={}", userId, httpSession,
                    getUserDOByIdResultDO);
                return "redirect:/" + StaticPath.COMMON_ERROR + "?" + getUserDOByIdResultDO.getMsg();
            }
        } catch (Exception e) {
            LOG.error("log out error, sessionId={}", httpSession.getId(), e);
            return "redirect:/" + StaticPath.COMMON_ERROR + "?" + ErrorText.SYSTEM_ERROR;
        }
        LOG.info("log out success, sessionId={}, userId={}", httpSession.getId(),
            SessionContentHolder.getSignInUserIdBySessionId(httpSession.getId()));
        SessionContentHolder.deleteSignInBySessionId(httpSession.getId());
        return TemplatePath.USER_LOGOUT_SUCCESS;
    }

    @Override
    @PostMapping("login")
    public String signin(@ModelAttribute UserDO userDO, HttpSession httpSession, Model model) {
        // 参数校验
        if (StringUtils.isBlank(userDO.getAccount()) || StringUtils.isBlank(userDO.getPassword())) {
            LOG.error("login fail, parameter invalid, userDO={}", userDO);
            return "redirect:/" + StaticPath.COMMON_ERROR + "?" + ErrorText.PARAMETER_INVALID;
        }
        try {
            ResultDO<Long> resultDO = userService.signin(userDO);
            if (resultDO.isSuccess() == false) {
                LOG.error("login fail, userDO={}, resultDO={}", userDO, resultDO);
                return "redirect:/" + StaticPath.COMMON_ERROR + "?" + resultDO.getMsg();
            }
            long userId = resultDO.getModule();
            if (userId <= 0) {
                LOG.error("login fail, userDO={}, sessionId={}, resultDO={}", userDO, httpSession.getId(), resultDO);
                return "redirect:/" + StaticPath.COMMON_ERROR + "?" + resultDO.getMsg();
            }
            // 授权
            ResultDO<Void> shiroAuthenticationResultDO = permissionService.shiroAuthentication(userId);
            if (shiroAuthenticationResultDO.isSuccess() == false) {
                LOG.error("shiro authentication fail, userDO={}, sessionId={}, shiroAuthenticationResultDO={}", userDO,
                    httpSession.getId(), shiroAuthenticationResultDO);
                return TemplatePath.USER_LOGIN;
            }
            ResultDO<Void> initPermissionResultDO = permissionService.initPermissionUserDOsByUserDO(userId);
            if (resultDO.isSuccess() == false) {
                LOG.error("sign up fail, userDO={}" + userDO);
                return "redirect:/" + StaticPath.COMMON_ERROR + "?" + initPermissionResultDO.getMsg();
            }
            // 登陆成功
            SessionContentHolder.addSignInUserId(httpSession.getId(), resultDO.getModule());
            LOG.info("login success, userDO={}, sessionId={}", userDO, httpSession.getId());
            String account = userDO.getAccount();
            model.addAttribute("account", account);
            return TemplatePath.USER_LOGIN_SUCCESS;
        } catch (Exception e) {
            LOG.error("login fail, userDO={}", userDO);
            return "redirect:/" + StaticPath.COMMON_ERROR + "?" + ErrorText.SYSTEM_ERROR;
        }
    }

    @Override
    @GetMapping("login")
    public String showSignin(HttpSession httpSession, Model model) {
        // 判断是否已经登陆，如果登陆直接跳转登陆成功页
        ResultDO<Long> resultDO = SessionContentHolder.judgeSignin(httpSession.getId());
        if (resultDO.isSuccess() == true) {
            long id = SessionContentHolder.getSignInUserIdBySessionId(httpSession.getId());
            LOG.info("user already signin, userId={}", id);
            String account = userService.getUserDOById(id).getModule().getAccount();
            model.addAttribute("account", account);
            return TemplatePath.USER_LOGIN_SUCCESS;
        }
        // 未登陆，跳转登陆页
        return TemplatePath.USER_LOGIN;
    }

    @Override
    @GetMapping("change-password")
    public String showChangePassword() {
        return TemplatePath.USER_UPDATE_PASSWORD;
    }

    @Override
    @GetMapping("change-password-success")
    public String showChangePasswordSuccess() {
        return TemplatePath.USER_UPDATE_PASSWORD_SUCCESS;
    }

    @Override
    @GetMapping("login-transit")
    public String showLoginSuccess() {
        return TemplatePath.USER_LOGIN_SUCCESS;
    }

    @Override
    @GetMapping("logout-transit")
    public String showLogoutSuccess() {
        return TemplatePath.USER_LOGOUT_SUCCESS;
    }

    @Override
    @PostMapping("register")
    public String register(@ModelAttribute UserVO userVO, HttpSession httpSession, Model model) {
        UserDO userDO = new UserDO();
        if (userVO.getPassword().equals(userVO.getConfirmpassword())) {
            userDO.setTag(UserTag.DELIVERYMAN);
            userDO.setAccount(userVO.getAccount());
            userDO.setPassword(userVO.getPassword());
            userDO.setEmail(userVO.getEmail());
            userDO.setName(userVO.getName());
            userDO.setAge(userVO.getAge());
            userDO.setSex(userVO.getSex());
            userDO.setPhone(userVO.getPhone());
            userDO.setWorkTime(10);
        }
        // 参数校验
        if (StringUtils.isBlank(userDO.getAccount()) || StringUtils.isBlank(userDO.getPassword())) {
            LOG.error("register fail, parameter invalid, userDO={}", userDO);
            return "redirect:/" + StaticPath.COMMON_ERROR + "?" + ErrorText.PARAMETER_INVALID;
        }
        try {
            ResultDO<Long> resultDO = userService.register(userDO);
            if (resultDO.isSuccess() == false) {
                LOG.error("register fail, userVO={}, resultDO={}", userVO, resultDO);
                return "redirect:/" + StaticPath.COMMON_ERROR + "?" + resultDO.getMsg();
            }
            // 注册成功
            LOG.info("register success, userDO={}, sessionId={}", userDO);
            String account = userDO.getAccount();
            model.addAttribute("account", account);
            return TemplatePath.USER_LOGIN;
        } catch (Exception e) {
            LOG.error("register fail, userVO={}", userVO);
            return "redirect:/" + StaticPath.COMMON_ERROR + "?" + ErrorText.SYSTEM_ERROR;
        }
    }

    @Override
    @PostMapping("modify-password")
    public String modifyPassword(@ModelAttribute UserModifyPasswordVO userModifyPasswordVO, HttpSession httpSession) {
        if (!userModifyPasswordVO.getModifypassword().equals(userModifyPasswordVO.getConfirmmodifypassword())) {
            LOG.error("register fail, parameter invalid, userModifyPasswordVO={},session={}", userModifyPasswordVO,
                httpSession);
            return "redirect:/" + StaticPath.COMMON_ERROR + "?" + ErrorText.PARAMETER_INVALID;
        }
        long userId = SessionContentHolder.getSignInUserIdBySessionId(httpSession.getId());
        if (StringUtils.isBlank(httpSession.getId())) {
            LOG.error("session error, session={}", httpSession);
            return "redirect:/" + StaticPath.COMMON_ERROR + "?" + ErrorText.PARAMETER_INVALID;
        }
        UserDO userDO;
        try {
            if (userId <= 0) {
                LOG.error("modify password error, userId <= 0, sessionId={}", httpSession.getId());
                return "redirect:/" + StaticPath.COMMON_ERROR + "?" + ErrorText.NO_SUCH_USER;
            }
            ResultDO<UserDO> getUserDOByIdResultDO = userService.getUserDOById(userId);
            userDO = getUserDOByIdResultDO.getModule();
            if (SHA256Util.SHA256(userModifyPasswordVO.getEnterpassword())
                .equals(getUserDOByIdResultDO.getModule().getPassword())) {
                ResultDO<Void> getModifyPasswordResultDO =
                    userService.ChangePassword(userDO, userModifyPasswordVO.getModifypassword());
                if (getModifyPasswordResultDO.isSuccess() == false) {
                    LOG.error("modify password fail, userId={}, session={}, resultDO={}",
                        getModifyPasswordResultDO.getModule(), httpSession, getUserDOByIdResultDO);
                    return "redirect:/" + StaticPath.COMMON_ERROR + "?" + getUserDOByIdResultDO.getMsg();
                }
            } else {
                LOG.error("register fail, enterpassword error, userModifyPasswordVO={},session={}",
                    userModifyPasswordVO, httpSession);
                return "redirect:/" + StaticPath.COMMON_ERROR + "?" + getUserDOByIdResultDO.getMsg();
            }

            if (getUserDOByIdResultDO.isSuccess() == false) {
                LOG.error("modify password fail, userId={}, session={}, resultDO={}", userDO, httpSession,
                    getUserDOByIdResultDO);
                return "redirect:/" + StaticPath.COMMON_ERROR + "?" + getUserDOByIdResultDO.getMsg();
            }

        } catch (Exception e) {
            LOG.error("modify password error, sessionId={}", httpSession.getId(), e);
            return "redirect:/" + StaticPath.COMMON_ERROR + "?" + ErrorText.SYSTEM_ERROR;
        }
        LOG.info("modify password success, UserModifyPasswordVO={}, sessionId={}", userModifyPasswordVO, httpSession);
        return TemplatePath.USER_UPDATE_PASSWORD_SUCCESS;

    }

    @Override
    @PostMapping("mail-authentication")
    public String mailAuthentication(@ModelAttribute FrontCaptchaVO mailCaptchaVO, HttpSession httpSession) {
        // 验证邮箱验证码
        if (StringUtils.isBlank(mailCaptchaVO.getCaptchaFromFront())) {
            LOG.error("mail authentication paramter illegal, mailCaptchaVO={}, sessionId={}", mailCaptchaVO,
                httpSession.getId());
            return "redirect:/" + StaticPath.COMMON_ERROR + "?" + ErrorText.PARAMETER_INVALID;
        }
        if (StringUtils.isBlank(httpSession.getId())) {
            LOG.error("mail authentication session is null, mailCaptchaVO={}, sessionId={}", mailCaptchaVO,
                httpSession.getId());
            return "redirect:/" + StaticPath.COMMON_ERROR + "?" + ErrorText.PARAMETER_INVALID;
        }
        // service输入参数准备
        UserDO userDO;
        try {
            long userId = SessionContentHolder.getSignInUserIdBySessionId(httpSession.getId());
            ResultDO<UserDO> getUserDOByIdResultDO = userService.getUserDOById(userId);
            if (getUserDOByIdResultDO.isSuccess() == false) {
                LOG.error("mail authentication get UserDO by id fail, getUserDOByIdResultDO={}, userId={}",
                    getUserDOByIdResultDO, userId);
                return "redirect:/" + StaticPath.COMMON_ERROR + "?" + getUserDOByIdResultDO.getMsg();
            }
            userDO = getUserDOByIdResultDO.getModule();
            if (userDO == null) {
                LOG.error("mail authentication userDO is null, userDO={}, userId={}", userDO, userId);
                return "redirect:/" + StaticPath.COMMON_ERROR + "?" + ErrorText.NO_SUCH_USER;
            }
        } catch (Exception e) {
            LOG.error("mail authentication session error, mailCaptchaVO={}, sessionId={}", mailCaptchaVO,
                httpSession.getId());
            return "redirect:/" + StaticPath.COMMON_ERROR + "?" + ErrorText.SYSTEM_ERROR;
        }
        String mail = null;
        String captchaFromFront = null;
        try {
            mail = userDO.getEmail();
            captchaFromFront = mailCaptchaVO.getCaptchaFromFront();
        } catch (Exception e) {
            LOG.error("mail authentication mail or captchaFromFront error, mail={}, captchaFromFront={}", mail,
                captchaFromFront);
            return "redirect:/" + StaticPath.COMMON_ERROR + "?" + ErrorText.SYSTEM_ERROR;
        }
        // 验证码托管
        boolean checkResult = VerificationCodeHolder.checkMailVerificationCode(mail, captchaFromFront);
        if (checkResult == false) {
            LOG.error("mail authentication verificationCode not match, mail={}, captchaFromFront={}", mail,
                captchaFromFront);
            return "redirect:/" + StaticPath.COMMON_ERROR + "?" + ErrorText.VERIFICATION_CODE_NOT_MATCH;
        }
        LOG.info("mail authentication captcha mathch success, mail={}, captchaFromFront", mail, captchaFromFront);
        SessionContentHolder.addMail(httpSession.getId(), mail);

        return TemplatePath.USER_UPDATE_MAIL;
    }

    @Override
    @PostMapping("update-mail")
    public String updateMail(UpdateMailVO updateMailVO, HttpSession httpSession) {
        // 先验证验证码
        if (StringUtils.isBlank(updateMailVO.getMail()) || StringUtils.isBlank(updateMailVO.getCaptchaFromFront())) {
            LOG.error("update mail paramter illegal, updateMailVO={}, seesinoId={}", updateMailVO, httpSession.getId());
            return "redirect:/" + StaticPath.COMMON_ERROR + "?" + ErrorText.PARAMETER_INVALID;
        }
        if (StringUtils.isBlank(httpSession.getId())) {
            LOG.error("update mail sessin error, updateMailVO={}, sessinId={}", updateMailVO, httpSession.getId());
            return "redirect:/" + StaticPath.COMMON_ERROR + "?" + ErrorText.PARAMETER_INVALID;
        }
        String mail = null;
        String captchaFromFront = null;
        try {
            mail = updateMailVO.getMail();
            captchaFromFront = updateMailVO.getCaptchaFromFront();
        } catch (Exception e) {
            LOG.error("update mail fail, mail or captchaFormFront error, mail={}, cpatchaFromFront={}", mail,
                captchaFromFront);
            return "redirect:/" + StaticPath.COMMON_ERROR + "?" + ErrorText.SYSTEM_ERROR;
        }
        boolean checkResult = VerificationCodeHolder.checkMailVerificationCode(mail, captchaFromFront);
        if (checkResult == false) {
            LOG.error("update mail verificationCode not match, mail={}, captchaFromFront={}", mail, captchaFromFront);
            return "redirect:/" + StaticPath.COMMON_ERROR + "?" + ErrorText.VERIFICATION_CODE_NOT_MATCH;
        }
        LOG.info("update mail verificationCode match success, updateMailVO={}, sessionId={}", updateMailVO,
            httpSession.getId());
        SessionContentHolder.addMail(httpSession.getId(), mail);

        // 修改原邮箱值
        UserDO userDO;
        try {
            long userId = SessionContentHolder.getSignInUserIdBySessionId(httpSession.getId());
            ResultDO<UserDO> getUserDOByIdResultDO = userService.getUserDOById(userId);
            if (getUserDOByIdResultDO.isSuccess() == false) {
                LOG.error("update mail get userDO by id fail, getUserDOByIdResultDO={}, updateMailVO={},sessionId={}",
                    getUserDOByIdResultDO, updateMailVO, httpSession.getId());
                return "redirect:/" + StaticPath.COMMON_ERROR + "?" + getUserDOByIdResultDO.getMsg();
            }
            userDO = getUserDOByIdResultDO.getModule();
            if (userDO == null) {
                LOG.error("update mail userDO is null, userDO={}, userId={}", userDO, userId);
                return "redirect:/" + StaticPath.COMMON_ERROR + "?" + ErrorText.NO_SUCH_USER;
            }
        } catch (Exception e) {
            LOG.error("update mail session error, updateMailVO={},sessionId={}", updateMailVO, httpSession.getId(), e);
            return "redirect:/" + StaticPath.COMMON_ERROR + "?" + ErrorText.SYSTEM_ERROR;
        }

        ResultDO<Void> resultDO = userService.updateMail(userDO, updateMailVO.getMail());
        if (resultDO.isSuccess() == false) {
            LOG.error("update mail fail, updateMailVO={}, resultDO={}", updateMailVO, resultDO);
            return "redirect:/" + StaticPath.COMMON_ERROR + "?" + resultDO.getMsg();
        }
        SessionContentHolder.deleteMailSessionBySessionId(httpSession.getId());
        // 重新种session
        SessionContentHolder.addSignInUserId(httpSession.getId(), userDO.getId());
        LOG.info("update mail success, updateMailVO={}, sessionId={}", updateMailVO, httpSession.getId());
        return TemplatePath.USER_UPDATE_MAIL_SUCCESS;

    }

    @Override
    @PostMapping("check-email-captcha")
    public String findPasswordByEmail(@ModelAttribute MailFindPasswordVO mailFindPasswordVO, HttpSession httpSession) {
        String mail = mailFindPasswordVO.getEmail();
        String chptcha = mailFindPasswordVO.getChptcha();
        // 参数校验
        if (StringUtils.isBlank(mail) || StringUtils.isBlank(chptcha)) {
            LOG.error("findpassword fail, parameter invalid, userEmailPasswordVO={}", mailFindPasswordVO);
            return "redirect:/" + StaticPath.COMMON_ERROR + "?" + ErrorText.PARAMETER_INVALID;
        }
        try {
            boolean check = VerificationCodeHolder.checkMailVerificationCode(mail, chptcha);
            if (check == false) {
                LOG.error("findpassword fail, parameter invalid, userEmailPasswordVO={}", mailFindPasswordVO);
                return "redirect:/" + StaticPath.COMMON_ERROR + "?" + ErrorText.PARAMETER_INVALID;
            }
            SessionContentHolder.addMail(httpSession.getId(), mail);
            LOG.error("findpassword success, userEmailPasswordVO={}", mailFindPasswordVO);
            return TemplatePath.FIND_UPDATE_PASSWORD;
        } catch (Exception e) {
            LOG.error("findpassword fail, userEmailPasswordVO={}", mailFindPasswordVO);
            return "redirect:/" + StaticPath.COMMON_ERROR + "?" + ErrorText.SYSTEM_ERROR;
        }

    }

    @Override
    @PostMapping("check-phone-captcha")
    public String findPasswordByPhone(@ModelAttribute PhoneFindPasswordVO phoneFindPasswordVO,
        HttpSession httpSession) {
        String phone = phoneFindPasswordVO.getPhone();
        String chptcha = phoneFindPasswordVO.getChptcha();
        // 参数校验
        if (StringUtils.isBlank(phone) || StringUtils.isBlank(chptcha)) {
            LOG.error("findpassword fail, parameter invalid, userEmailPasswordVO={}", phoneFindPasswordVO);
            return "redirect:/" + StaticPath.COMMON_ERROR + "?" + ErrorText.PARAMETER_INVALID;
        }
        try {
            boolean check = VerificationCodeHolder.checkPhoneVerificationCode(phone, chptcha);
            if (check == false) {
                LOG.error("findpassword fail, parameter invalid, userEmailPasswordVO={}", phoneFindPasswordVO);
                return "redirect:/" + StaticPath.COMMON_ERROR + "?" + ErrorText.PARAMETER_INVALID;
            }
            SessionContentHolder.addPhone(httpSession.getId(), phone);
            LOG.error("findpassword success, parameter invalid, userEmailPasswordVO={}", phoneFindPasswordVO);
            return TemplatePath.FIND_UPDATE_PASSWORD;
        } catch (Exception e) {
            LOG.error("findpassword fail, userEmailPasswordVO={}", phoneFindPasswordVO);
            return "redirect:/" + StaticPath.COMMON_ERROR + "?" + ErrorText.SYSTEM_ERROR;
        }
    }

    @Override
    @PostMapping("find-update-password")
    public String findUpdatePassword(FindPasswordVO findPasswordVO, HttpSession httpSession) {
        // 参数校验
        String newpassword = findPasswordVO.getNewpassword();
        String confirmnewpassword = findPasswordVO.getConfirmnewpassword();
        if (StringUtils.isBlank(newpassword) || StringUtils.isBlank(confirmnewpassword)) {
            LOG.error("update password fail, parameter invalid, findPasswordVO={}", findPasswordVO);
            return "redirect:/" + StaticPath.COMMON_ERROR + "?" + ErrorText.PARAMETER_INVALID;
        }
        try {
            if (SessionContentHolder.getMail(httpSession.getId()) != null) {
                if (!newpassword.equals(confirmnewpassword)) {
                    String mail = SessionContentHolder.getMail(httpSession.getId());
                    ResultDO<UserDO> getUserDOByMail = userService.getUserDOByMail(mail);
                    ResultDO<Void> updatePassword =
                        userService.ChangePassword(getUserDOByMail.getModule(), newpassword);
                    if (updatePassword.isSuccess() == false) {
                        LOG.error("update password fail, userId={}, session={}, resultDO={}",
                            updatePassword.getModule(), httpSession, updatePassword);
                        return "redirect:/" + StaticPath.COMMON_ERROR + "?" + updatePassword.getMsg();
                    }
                } else {
                    LOG.error("find password fail, newpassword error, findPasswordVO={},session={}", findPasswordVO,
                        httpSession);
                    return "redirect:/" + StaticPath.COMMON_ERROR + "?" + ErrorText.PARAMETER_INVALID;
                }
                if (SessionContentHolder.getPhone(httpSession.getId()) != null) {
                    if (!newpassword.equals(confirmnewpassword)) {
                        String phone = SessionContentHolder.getPhone(httpSession.getId());
                        ResultDO<UserDO> getUserDOByPhone = userService.getUserDOByPhone(phone);
                        ResultDO<Void> updatePassword =
                            userService.ChangePassword(getUserDOByPhone.getModule(), newpassword);
                        if (updatePassword.isSuccess() == false) {
                            LOG.error("update password fail, userId={}, session={}, resultDO={}",
                                updatePassword.getModule(), httpSession, updatePassword);
                            return "redirect:/" + StaticPath.COMMON_ERROR + "?" + updatePassword.getMsg();
                        }
                    } else {
                        LOG.error("find password fail, newpassword error, findPasswordVO={},session={}", findPasswordVO,
                            httpSession);
                        return "redirect:/" + StaticPath.COMMON_ERROR + "?" + ErrorText.PARAMETER_INVALID;
                    }
                }
            }
        } catch (Exception e) {
            LOG.error("update password fail, findPasswordVO={}", findPasswordVO);
            return "redirect:/" + StaticPath.COMMON_ERROR + "?" + ErrorText.SYSTEM_ERROR;
        }
        LOG.info("update password success, findPasswordVO={}, sessionId={}", findPasswordVO, httpSession);
        return TemplatePath.USER_UPDATE_PASSWORD_SUCCESS;
    }

    @Override
    @GetMapping("mail-authentication")
    public String showMailAuthentication() {
        return TemplatePath.USER_MAIL_AUTHENTICATION;
    }

    @Override
    @PostMapping("phone-authentication")
    public String phoneAuthentication(FrontCaptchaVO phoneCaptchaVO, HttpSession httpSession) {
        if (StringUtils.isBlank(phoneCaptchaVO.getCaptchaFromFront())) {
            LOG.error("phone authentication paramter illegal, phoneCaptchaVO={}, sessionId={}", phoneCaptchaVO,
                httpSession.getId());
            return "redirect:/" + StaticPath.COMMON_ERROR + "?" + ErrorText.PARAMETER_INVALID;
        }
        if (StringUtils.isBlank(httpSession.getId())) {
            LOG.error("phone authentication session is null, phoneCaptchaVO={}, sessionId={}", phoneCaptchaVO,
                httpSession.getId());
            return "redirect:/" + StaticPath.COMMON_ERROR + "?" + ErrorText.PARAMETER_INVALID;
        }
        UserDO userDO;
        long userId = SessionContentHolder.getSignInUserIdBySessionId(httpSession.getId());
        ResultDO<UserDO> getUserDOByIdResultDO = userService.getUserDOById(userId);
        if (getUserDOByIdResultDO.isSuccess() == false) {
            LOG.error("phone authentication session is null, getUserDOByIdResultDO={}, sessionId={}",
                getUserDOByIdResultDO, httpSession.getId());
            return "redirect:/" + StaticPath.COMMON_ERROR + "?" + getUserDOByIdResultDO.getMsg();
        }
        userDO = getUserDOByIdResultDO.getModule();
        if (userDO == null) {
            LOG.error("phone authentication userDO is null ,userDO={}, sessionId={}", userDO, httpSession.getId());
            return "redirect:/" + StaticPath.COMMON_ERROR + "?" + ErrorText.NO_SUCH_USER;
        }
        String phone = null;
        String captchaFromFront = null;
        try {
            phone = userDO.getPhone();
            captchaFromFront = phoneCaptchaVO.getCaptchaFromFront();
        } catch (Exception e) {
            LOG.error("phone authentication phone or catchaFromFront error, userDO={}, phoneCaptchaVO={}", userDO,
                phoneCaptchaVO);
            return "redirect:/" + StaticPath.COMMON_ERROR + ErrorText.SYSTEM_ERROR;
        }
        boolean checkPhoneVerificationCode = VerificationCodeHolder.checkPhoneVerificationCode(phone, captchaFromFront);
        if (checkPhoneVerificationCode == false) {
            LOG.error("phone authentication verificationCode not match, phone={}, captchaFromFront={}", phone,
                captchaFromFront);
            return "redirect:/" + StaticPath.COMMON_ERROR + "?" + ErrorText.VERIFICATION_CODE_NOT_MATCH;
        }
        LOG.info("phone authentication verificationCode match success, phone={}, captchaFromFront={}", phone,
            captchaFromFront);
        SessionContentHolder.addPhone(httpSession.getId(), phone);
        return TemplatePath.USER_UPDATE_PHONE;
    }

    @Override
    @PostMapping("update-phone")
    public String updatePhone(@ModelAttribute UpdatePhoneVO updatePhoneVO, HttpSession httpSession) {
        if (StringUtils.isBlank(updatePhoneVO.getPhone()) || StringUtils.isBlank(updatePhoneVO.getCaptchaFromFront())) {
            LOG.error("update phone paramter illegal, updatePhoneVO={}, sessionId={}", updatePhoneVO,
                httpSession.getId());
            return "redirect:/" + StaticPath.COMMON_ERROR + "?" + ErrorText.PARAMETER_INVALID;
        }
        if (StringUtils.isBlank(httpSession.getId())) {
            LOG.error("update phone sessionId is null, updatePhoneVO={}, sessionId={}", updatePhoneVO,
                httpSession.getId());
            return "redirect:/" + StaticPath.COMMON_ERROR + "?" + ErrorText.PARAMETER_INVALID;
        }
        String phone = null;
        String captchaFromFront = null;
        try {
            phone = updatePhoneVO.getPhone();
            captchaFromFront = updatePhoneVO.getCaptchaFromFront();
        } catch (Exception e) {
            LOG.error("update phone phone or captchaFromFront error, phone={}, captchaFromFront={}", phone,
                captchaFromFront);
            return "redirect:/" + StaticPath.COMMON_ERROR + "?" + ErrorText.SYSTEM_ERROR;
        }
        boolean result = VerificationCodeHolder.checkPhoneVerificationCode(phone, captchaFromFront);
        if (result == false) {
            LOG.error("update phone verificationCode not match, phone={}, captchaFromFront={}", phone,
                captchaFromFront);
            return "redirect:/" + StaticPath.COMMON_ERROR + ErrorText.VERIFICATION_CODE_NOT_MATCH;
        }
        LOG.info("update phone verificationCode match success,updatePhoneVO={}, sessionId={}", updatePhoneVO,
            httpSession.getId());
        SessionContentHolder.addPhone(httpSession.getId(), phone);

        UserDO userDO;
        try {
            long userId = SessionContentHolder.getSignInUserIdBySessionId(httpSession.getId());
            ResultDO<UserDO> getUserDOByIdResultDO = userService.getUserDOById(userId);
            if (getUserDOByIdResultDO.isSuccess() == false) {
                LOG.error(
                    "update phone get UserDO by Id fail, getUserDOByIdResultDO={}, updatePhoneVO={}, sessionId={}",
                    getUserDOByIdResultDO, updatePhoneVO, httpSession.getId());
                return "redirect:/" + StaticPath.COMMON_ERROR + getUserDOByIdResultDO.getMsg();
            }
            userDO = getUserDOByIdResultDO.getModule();
            if (userDO == null) {
                LOG.error("update phone userDO is null, userDO={}, userId={} ", userDO, userId);
                return "redirect:/" + StaticPath.COMMON_ERROR + ErrorText.NO_SUCH_USER;
            }
        } catch (Exception e) {
            LOG.error("update phone session error, updatePhoneVO={}, sessionId={}", updatePhoneVO, httpSession.getId(),
                e);
            return "redirect:/" + StaticPath.COMMON_ERROR + ErrorText.SYSTEM_ERROR;
        }
        ResultDO<Void> updatePhoneResultDO = userService.updatePhone(userDO, updatePhoneVO.getPhone());
        if (updatePhoneResultDO.isSuccess() == false) {
            LOG.error("update phone fail, updatePhoneResultDO={}, userDO={}", updatePhoneResultDO, userDO);
            return "redirect:/" + StaticPath.COMMON_ERROR + "?" + updatePhoneResultDO.getMsg();
        }
        SessionContentHolder.deletePhoneSessionBySessionId(httpSession.getId());

        SessionContentHolder.addSignInUserId(httpSession.getId(), userDO.getId());
        LOG.info("update phone success, updatePhoneVO={}, sessionId={}", updatePhoneVO, httpSession.getId());
        return TemplatePath.USER_UPDATE_PHONE_SUCCESS;
    }

    @Override
    public String showPhoneAuthentication() {
        return TemplatePath.USER_PHONE_AUTHENTICATION;
    }

}
